
package biblio.service.author;


import biblio.dao.AuthorDAO;
import biblio.domain.Author;
import biblio.util.SourceName;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Provides data to editing and deleting.
 * 
 * @author mephisto
 */
@ManagedBean(name = "authorList")
@ViewScoped
public class AuthorList implements Serializable
{
    public void remove()
    {
        Author tmp = allItems.get(currentAuthorIndex);
        authorService.delete(tmp);
        allItems.remove(tmp);
    }

    public void store()
    {
        authorService.update(editedAuthor);
        allItems.set(currentAuthorIndex, editedAuthor);
    }

    public List<Author> getAllItems()
    {
        synchronized (this)
        {
            if (allItems == null)
            {
                AuthorDAO authorDAO = (AuthorDAO)appContext.getBean("authorDAO");
                allItems = authorDAO.selectAll();
            }
        }
        return allItems;
    }

    public int getCurrentAuthorIndex()
    {
        return currentAuthorIndex;
    }

    public void setCurrentAuthorIndex(int currentAuthorIndex)
    {
        this.currentAuthorIndex = currentAuthorIndex;
    }

    public Author getEditedAuthor()
    {
        return editedAuthor;
    }

    public void setEditedAuthor(Author editedAuthor)
    {
        this.editedAuthor = editedAuthor;
    }

    public int getPage()
    {
        return page;
    }

    public void setPage(int page)
    {
        this.page = page;
    }

    public void setAuthorService(AuthorServiceImpl authorService)
    {
        this.authorService = authorService;
    }

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static final long serialVersionUID = -3832235532261771583L;
    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(AuthorList.class);
    private int page = 1;
    private List<Author> allItems = null;
    private int currentAuthorIndex;
    private Author editedAuthor;
    @ManagedProperty(value="#{authorService}")
    private AuthorServiceImpl authorService;
}
